import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { mockRandomPersons, mockRandomShifts } from '../schedule-render/utils/helper';
import { useCalendarStore } from './calendar';

export const useScheduleStore = defineStore('schedule', () => {
  // 排班数据状态
  const schedules = ref<PersonSchedule[]>([]);

  // 初始化排班数据
  const initializeSchedules = () => {
    const calendarStore = useCalendarStore();
    const startDate = new Date(calendarStore.dateRange.start);
    const todayOffset = Math.floor((+new Date() - +startDate) / (60 * 60 * 24 * 1000));

    const persons = mockRandomPersons(10);
    const scheduleData = persons.map(person => ({
      person,
      shifts: mockRandomShifts(person.id, Math.floor(Math.random() * 4) + 1, todayOffset),
    }));
    schedules.value = scheduleData;
  };

  // 更新排班数据
  const updateSchedules = (newSchedules: PersonSchedule[]) => {
    schedules.value = newSchedules;
  };

  // 添加新的排班
  const addSchedule = (personId: string, shift: Shift) => {
    const personSchedule = schedules.value.find(s => s.person.id === personId);
    if (personSchedule) {
      personSchedule.shifts.push(shift);
    } else {
      // 如果人员不存在，创建新的排班记录
      schedules.value.push({
        person: { id: personId, name: `Person ${personId}` },
        shifts: [shift],
      });
    }
  };

  // 更新排班
  const updateShift = (personId: string, shiftId: string, updatedShift: Partial<Shift>) => {
    const personSchedule = schedules.value.find(s => s.person.id === personId);
    if (personSchedule) {
      const shiftIndex = personSchedule.shifts.findIndex(s => s.id === shiftId);
      if (shiftIndex !== -1) {
        personSchedule.shifts[shiftIndex] = { ...personSchedule.shifts[shiftIndex], ...updatedShift };
      }
    }
  };

  // 删除排班
  const removeShift = (personId: string, shiftId: string) => {
    const personSchedule = schedules.value.find(s => s.person.id === personId);
    if (personSchedule) {
      personSchedule.shifts = personSchedule.shifts.filter(s => s.id !== shiftId);
    }
  };

  // 行重排序
  const reorderSchedules = (fromIndex: number, toIndex: number) => {
    if (fromIndex === toIndex) {
      return;
    }

    const newSchedules = [...schedules.value];
    const [movedItem] = newSchedules.splice(fromIndex, 1);
    newSchedules.splice(toIndex, 0, movedItem);
    schedules.value = newSchedules;
  };

  // 计算属性：获取去重后的人员列表
  const uniquePersons = computed(() => {
    const uniquePersonMap = new Map<string, PersonSchedule>();

    schedules.value.forEach(schedule => {
      const personId = schedule.person.id;
      if (!uniquePersonMap.has(personId)) {
        uniquePersonMap.set(personId, schedule);
      } else {
        const existingSchedule = uniquePersonMap.get(personId)!;
        existingSchedule.shifts = [...existingSchedule.shifts, ...schedule.shifts];
      }
    });

    return Array.from(uniquePersonMap.values());
  });

  return {
    schedules,
    uniquePersons,
    initializeSchedules,
    updateSchedules,
    addSchedule,
    updateShift,
    removeShift,
    reorderSchedules,
  };
});
